﻿using System.Web.Mvc;
using BLL.Security;
using BLL.Services.Ratings;
using Web.Infrastructure;

namespace Web.Controllers
{
    /// <summary>
    /// The rating controller.
    /// </summary>
    public partial class RatingController : FrontendController
    {
        private readonly IEnvironmentContext _environmentContext;

        private readonly IRatingService _ratingService;

        public RatingController(IEnvironmentContext environmentContext, IRatingService ratingService)
        {
            _environmentContext = environmentContext;
            _ratingService = ratingService;
        }

        public virtual ActionResult RatingTemplate()
        {
            return BackBoneView(MVC.Rating.Views.RatingTemplate);
        }

        public virtual ActionResult Rate(int? bookId, int? ratingValue)
        {
            if (bookId.HasValue && ratingValue.HasValue)
            {
                var rating = new Rating
                    {
                        BookId = bookId.Value,
                        RateValue = ratingValue.Value,
                        UserId = _environmentContext.User.UserId
                    };
                _ratingService.SetRating(rating);
                var currentBookRating = new { Rating = _ratingService.GetBookRating(bookId.Value).Rating };
                return Json(currentBookRating, JsonRequestBehavior.AllowGet);
            }
            var errorBookRating = new { RatingView = 0 };
            return Json(errorBookRating, JsonRequestBehavior.AllowGet);
        }
    }
}
